package com.lobstar.xrpc.server.listener;

import java.lang.reflect.InvocationTargetException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lobstar.xrpc.common.listener.RequestListener;
import com.lobstar.xrpc.common.listener.ResponseListener;
import com.lobstar.xrpc.common.po.SMessage;
import com.lobstar.xrpc.common.po.Task;
import com.lobstar.xrpc.server.cache.TaskCache;
import com.lobstar.xrpc.server.handler.task.TaskCallback;
import com.lobstar.xrpc.server.threads.RequestHandleThreadPool;
import com.lobstar.xrpc.service.base.ServiceInvoker;
import com.lobstar.xrpc.service.utils.JsonUtils;

import io.netty.channel.ChannelHandlerContext;

public class DefaultServiceListener {
	private static Logger logger = LoggerFactory.getLogger(DefaultServiceListener.class);
	public static OnlineListener online() {
		return new OnlineListener() {
			@Override
			public void handle(String id) {
				logger.info("{} into init handle",id);
			}
		};
	}
	public static OfflineListener offline() {
		return new OfflineListener() {
			@Override
			public void handle(String id) {
				logger.info("{} into offline handle",id);
			}
		};
	}
//	public static RequestListener request() {
//		return new RequestListener() {
//			@Override
//			public void handle(ChannelHandlerContext ctx,SMessage smessage) {
//				RequestHandleThreadPool.handleRequest(()->{
//					Object ret = null;
//					Object ex = null;
//					//记录msg的id标识返回对象
//					try {
//						if(invoker.hasMethod(smessage)) {
//							try {
//								ret = invoker.invoke(smessage);
//								smessage.addAttribute("_ret", JsonUtils.toJson(ret));
//							}catch(Exception e) {
//								if(e.getClass() == InvocationTargetException.class) {
//									ex = ((InvocationTargetException)e).getTargetException().toString();
//								}else {
//									ex = e.toString();
//								}
//							}
//						}else {
//							ex = "no method";
//						}
//						if(ex != null) {
//							smessage.addAttribute("_exception", ex);
//						}
//						ctx.channel().writeAndFlush(smessage.buildResponse());
//					}catch(Exception e) {
//						logger.error("request",e);
//					}
//				});
//			}
//		};
//	}
	public static ResponseListener response() {
		return new ResponseListener() {
			@Override
			public void handle(ChannelHandlerContext ctx,SMessage message) {
				String id = message.getId();
				Task task = TaskCache.find(id);
				if(task != null) {
					TaskCallback callback = task.getCallback();
					if(message.getParams().containsKey("_exception")) {
						if(callback != null) {
							callback.handleException(message.getParams().get("_exception").toString());
						}
					}else
					if(message.getParams().containsKey("_ret")) {
						String ret = message.getParams().get("_ret").toString();
						if(callback != null) {
							callback.callback(ret);
						}
					}else {
						if(callback != null) {
							callback.callback(null);
						}
					}
				}
			}

		};
	}
}
